﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace EBA.Data
{
    public abstract class UnitOfWork : IUnitOfWork
    {
        public abstract ObjectContext ObjectContext { get; }

        #region IUnitOfWork

        protected virtual DbTransaction Transaction { get; set; }

        public virtual void BeginTransaction()
        {
            if (this.ObjectContext.Connection.State != System.Data.ConnectionState.Open)
            {
                this.ObjectContext.Connection.Open();
            }

            this.Transaction = this.ObjectContext.Connection.BeginTransaction();
        }

        public virtual void CommitTransaction()
        {
            if (this.Transaction == null)
            {
                throw new InvalidOperationException("The transaction has not been started.");
            }
            else
            {
                this.Transaction.Commit();
                this.OnSubmittedChanges();
            }
        }

        public virtual void EndTransaction()
        {
            if (this.Transaction != null)
            {
                this.Transaction.Dispose();
                this.Transaction = null;
            }
        }

        public virtual void RollbackTransaction()
        {
            if (this.Transaction.Connection != null)
            {
                this.Transaction.Rollback();
            }
        }

        public virtual void SubmitChanges()
        {
            try
            {
                this.ObjectContext.SaveChanges();
                if (this.Transaction == null)
                {
                    this.OnSubmittedChanges();
                }
            }
            catch (OptimisticConcurrencyException ex)
            {
                throw new DBConcurrencyException("", ex);
            }

        }

        protected virtual void OnSubmittedChanges()
        {
            if (this.SubmittedChanges != null)
            {
                this.SubmittedChanges(this, EventArgs.Empty);
            }
        }

        public event EventHandler SubmittedChanges;
        #endregion
    }
}
